<template>
  <div class="app-container">
    <div style="margin-bottom: 20px; float: left">
      <el-form :inline="true"
               :model="queryParams"
               ref="queryParams"
               label-position="right"
               size="small"
               class="demo-form-inline">
        <!-- 新增过滤条件 -->
        <el-form-item label="环境：" prop="env">
          <el-radio-group v-model="queryParams.env">
            <el-radio-button v-for="(item, index) in envFilters" :key="index" :label="item">{{ item }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="数据库类型：" prop="db_type">
          <el-radio-group v-model="queryParams.db_type">
            <el-radio-button v-for="(item, index) in dbTypeFilters" :key="index" :label="item">{{ item }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="主机名：" prop="hostname">
          <el-input v-model="queryParams.hostname" clearable></el-input>
        </el-form-item>
        <el-form-item label="IP：" prop="ip">
          <el-input v-model="queryParams.ip" clearable></el-input>
        </el-form-item>
        <el-form-item label="搜索：">
          <el-input v-model="queryParams.search" placeholder="支持多条件搜索" clearable style="width: 250px;"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter(queryParams)">查询</el-button>
          <el-button @click="resetForm('queryParams')">重置</el-button>
          <el-button type="success" @click="handleAdd" style="margin-left: 20px" >新增</el-button>
        </el-form-item>


      </el-form>

    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column
        v-for="(column, index) in columns"
        :key="index"
        :align="column.align || 'left'"
        :label="column.label"
        :width="column.width"
        :fixed="column.fixed"
      >
        <template slot-scope="scope">
          <!-- 处理时间字段，添加图标 -->
          <template v-if="['create_time', 'update_time'].includes(column.prop)">
            <span>{{ scope.row[column.prop] }}</span>
          </template>
          <template v-else>
            {{ scope.row[column.prop] }}
          </template>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="60%" style="margin-top:-80px">
      <el-form ref="dataForm" :rules="rules" :model="temp" size="small"
               label-position="right" label-width="120px" label-suffix=" :">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="环境" prop="env">
              <el-radio-group v-model="temp.env">
                <el-radio-button v-for="(item, index) in envOptions" :key="index" :label="item" :value="item">{{ item }}</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="主机名" prop="hostname">
              <el-input v-model="temp.hostname"/>
            </el-form-item>
            <el-form-item label="SN" prop="sn">
              <el-input v-model="temp.sn"/>
            </el-form-item>
            <el-form-item label="IP地址" prop="ip">
              <el-input v-model="temp.ip"/>
            </el-form-item>

            <el-form-item label="系统磁盘类型" prop="system_disk_type">
              <el-input v-model="temp.system_disk_type"/>
            </el-form-item>
            <el-form-item label="系统磁盘大小" prop="system_disk_size">
              <el-input v-model.number="temp.system_disk_size"/>
            </el-form-item>
            <el-form-item label="操作系统" prop="os">
              <el-input v-model="temp.os"/>
            </el-form-item>
            <el-form-item label="操作系统版本" prop="os_version">
              <el-input v-model="temp.os_version"/>
            </el-form-item>
            <el-form-item label="区域" prop="region">
              <el-input v-model="temp.region"/>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="temp.status" class="filter-item" placeholder="请选择" clearable style="width: 150px">
                <el-option v-for="(item,index) in statusList" :key="index" :label="item" :value="item"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据库类型" prop="db_type">
              <el-radio-group v-model="temp.db_type">
                <el-radio-button v-for="(item, index) in dbTypeOptions" :key="index" :label="item" :value="item">{{ item }}</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="规格" prop="specification">
              <el-input v-model="temp.specification"/>
            </el-form-item>
            <el-form-item label="CPU" prop="cpu">
              <el-input v-model.number="temp.cpu"/>
            </el-form-item>
            <el-form-item label="内存" prop="memory">
              <el-input v-model.number="temp.memory"/>
            </el-form-item>
            <el-form-item label="数据磁盘类型" prop="data_disk_type">
              <el-input v-model="temp.data_disk_type"/>
            </el-form-item>
            <el-form-item label="数据磁盘大小" prop="data_disk_size">
              <el-input v-model.number="temp.data_disk_size"/>
            </el-form-item>

            <el-form-item label="服务器制造商" prop="server_manufacturer">
              <el-input v-model="temp.server_manufacturer"/>
            </el-form-item>
            <el-form-item label="部署类型" prop="deploy_type">
              <el-input v-model="temp.deploy_type"/>
            </el-form-item>

            <el-form-item label="可用区" prop="zone">
              <el-input v-model="temp.zone"/>
            </el-form-item>

            <el-form-item label="备注" prop="remark">
              <el-input v-model="temp.remark"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import {createServer, deleteServer, getServerList, updateServer} from '@/api/meta-data'

export default {
  data() {
    return {
      list: null,
      listLoading: true,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      columns: [
        { prop: "id", label: "ID", width: 95, fixed: "left" },
        { prop: "hostname", label: "主机名", width: 135, fixed: "left" },
        { prop: "sn", label: "序列号", width: 110 },
        { prop: "ip", label: "IP地址", width: 120 },
        { prop: "status", label: "状态", width: 110 },
        { prop: "db_type", label: "数据库类型", width: 100 },
        { prop: "env", label: "环境", width: 100 },
        { prop: "specification", label: "规格", width: 150 },
        { prop: "cpu", label: "CPU", width: 80 },
        { prop: "memory", label: "内存", width: 80 },
        { prop: "system_disk_type", label: "系统磁盘类型", width: 120 },
        { prop: "system_disk_size", label: "系统磁盘大小", width: 120 },
        { prop: "data_disk_type", label: "数据磁盘类型", width: 120 },
        { prop: "data_disk_size", label: "数据磁盘大小", width: 120 },
        { prop: "os", label: "操作系统", width: 100 },
        { prop: "os_version", label: "操作系统版本", width: 120 },
        { prop: "server_manufacturer", label: "服务器制造商", width: 150 },
        { prop: "deploy_type", label: "部署类型", width: 100 },
        { prop: "region", label: "区域", width: 120 },
        { prop: "zone", label: "可用区", width: 120 },
        { prop: "remark", label: "备注", width: 200 },
        { prop: "create_time", label: "创建时间", width: 200 },
        { prop: "update_time", label: "更新时间", width: 200 },
      ],
      queryParams: {
        search: '',
        hostname: '',
        env: 'ALL',
        ip: '',
        db_type: 'ALL',
      },
      envFilters: ['ALL', 'DEV', 'FAT', 'PRO'],
      envOptions: [ 'DEV', 'FAT', 'PRO'],
      dbTypeFilters: ['ALL', 'MySQL', 'PostgreSQL'],
      dbTypeOptions: ['MySQL', 'PostgreSQL'],
      dialogFormVisible: false,
      dialogStatus: 'create',
      textMap: {
        create: '新增',
        edit: '编辑'
      },
      temp: {
        id: null,
        hostname: '',
        sn: '',
        ip: '',
        env: '',
        specification: '',
        cpu: null,
        memory: null,
        system_disk_type: '',
        system_disk_size: null,
        data_disk_type: '',
        data_disk_size: null,
        os: '',
        os_version: '',
        server_manufacturer: '',
        deploy_type: '',
        region: '',
        zone: '',
        db_type: 'MySQL',
        status: '',
        remark: ''
      },
      statusList: ['online', 'offline'],
      rules : {
        hostname: [{ required: true, message: '请输入主机名', trigger: 'blur' }],
        sn: [{ required: true, message: '请输入SN', trigger: 'blur' }],
        ip: [
          { required: true, message: '请输入IP地址', trigger: 'blur' },
          { pattern: /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/, message: '请输入有效的IP地址', trigger: 'blur' }
        ],
        env: [{ required: true, message: '请选择环境', trigger: 'change' }],
        specification: [{ required: true, message: '请输入规格', trigger: 'blur' }],
        cpu: [
          { required: true, message: '请输入CPU信息', trigger: 'blur' },
          { type: 'number', message: '请输入有效的数字', trigger: 'blur' }
        ],
        memory: [
          { required: true, message: '请输入内存信息', trigger: 'blur' },
          { type: 'number', message: '请输入有效的数字', trigger: 'blur' }
        ],
        system_disk_type: [{ required: true, message: '请输入系统磁盘类型', trigger: 'blur' }],
        system_disk_size: [
          { required: true, message: '请输入系统磁盘大小', trigger: 'blur' },
          { type: 'number', message: '请输入有效的数字', trigger: 'blur' }
        ],
        data_disk_type: [{ required: true, message: '请输入数据磁盘类型', trigger: 'blur' }],
        data_disk_size: [
          { required: true, message: '请输入数据磁盘大小', trigger: 'blur' },
          { type: 'number', message: '请输入有效的数字', trigger: 'blur' }
        ],
        os: [{ required: true, message: '请输入操作系统', trigger: 'blur' }],
        os_version: [{ required: true, message: '请输入操作系统版本', trigger: 'blur' }],
        server_manufacturer: [{ required: true, message: '请输入服务器制造商', trigger: 'blur' }],
        deploy_type: [{ required: true, message: '请输入部署类型', trigger: 'blur' }],
        region: [{ required: true, message: '请输入区域', trigger: 'blur' }],
        zone: [{ required: true, message: '请输入可用区', trigger: 'blur' }],
        db_type: [{ required: true, message: '请选择数据库类型', trigger: 'change' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
        remark: [{ required: false, message: '', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      const params = {
        page: this.currentPage,
        page_size: this.pageSize,
        ...this.queryParams
      }
      if(this.queryParams.env === 'ALL'){
        params.env = null
      }
      if(this.queryParams.db_type === 'ALL'){
        params.db_type = null
      }
      getServerList(params).then(response => {
        this.list = response.data.records
        this.total = response.data.count
        this.listLoading = false
      })
    },
    handleFilter(params) {
      this.currentPage = 1
      this.fetchData()
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.queryParams = {
        search: '',
        hostname: '',
        env: 'ALL',
        ip: '',
        db_type: 'ALL',
      }
      this.currentPage = 1
      this.fetchData()
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize
      this.fetchData()
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage
      this.fetchData()
    },

    handleDelete(id) {
      this.$confirm('确定要删除这条记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用删除接口
        deleteServer(id).then(() => {
          this.fetchData()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleEdit(row) {
      this.dialogStatus = 'edit'
      this.temp = { ...row }
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    handleAdd() {
      this.dialogStatus = 'create'
      this.temp = {
        id: null,
        hostname: '',
        sn: '',
        ip: '',
        env: 'DEV',
        specification: '',
        cpu: null,
        memory: null,
        system_disk_type: '',
        system_disk_size: null,
        data_disk_type: '',
        data_disk_size: null,
        os: '',
        os_version: '',
        server_manufacturer: '',
        deploy_type: '',
        region: '',
        zone: '',
        db_type: 'MySQL',
        status: '',
        remark: ''
      }
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          createServer(this.temp).then(() => {
            this.dialogFormVisible = false
            this.fetchData()
            this.$message({
              type: 'success',
              message: '新增成功'
            })
          }).catch(() => {
            this.$message({
              type: 'error',
              message: '新增失败'
            })
          })
        } else {
          return false
        }
      })
    },
    updateData() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          updateServer(this.temp.id, this.temp).then(() => {
            this.dialogFormVisible = false
            this.fetchData()
            this.$message({
              type: 'success',
              message: '更新成功'
            })
          }).catch(() => {
            this.$message({
              type: 'error',
              message: '更新失败'
            })
          })
        } else {
          return false
        }
      })
    }

  }
}
</script>

<style scoped>
/* 可以添加一些自定义样式 */
</style>
